package com.lanhe.common.utils;


import com.fasterxml.jackson.dataformat.xml.XmlMapper;
import com.lanhe.common.utils.wechat.vo.PrePayNotifyDataVo;
import com.thoughtworks.xstream.XStream;
import com.thoughtworks.xstream.core.util.QuickWriter;
import com.thoughtworks.xstream.io.HierarchicalStreamWriter;
import com.thoughtworks.xstream.io.xml.PrettyPrintWriter;
import com.thoughtworks.xstream.io.xml.XppDriver;

import java.io.IOException;
import java.io.Writer;

public class XmlUtils {
	/**
	 * 是否使用map转换器
	 */
	public static Boolean useConverter = true;

	/**
	 * 扩展xstream，使其支持CDATA块
	 */
	private static XStream xStream = new XStream(new XppDriver() {
		public HierarchicalStreamWriter createWriter(Writer out) {
			return new PrettyPrintWriter(out) {
				// 对所有xml节点的转换都增加CDATA标记
				boolean cdata = true;

				@Override
				public void startNode(String name, Class clazz) {
					super.startNode(name, clazz);
				}

				@Override
				public String encodeNode(String name) {
					return name;
				}

				@Override
				protected void writeText(QuickWriter writer, String text) {
					if (cdata) {
						writer.write("<![CDATA[");
						writer.write(text);
						writer.write("]]>");
					} else {
						writer.write(text);
					}
				}
			};
		}
	});


	private static <T> XStream getXStream(Class<T> t) {
		//处理注解
		xStream.processAnnotations(t);
		return xStream;
	}

	/**
	 * XML转对象
	 *
	 * @param clazz 对象类
	 * @param xml   xml字符串
	 * @param <T>   T
	 * @return
	 */
	public static <T> T parseFromXml(Class<T> clazz, String xml) {
		//将XML字符串转为bean对象
		T t = (T) xStream.fromXML(xml);
		return t;
	}

	/**
	 * XML转对象
	 *
	 * @param xml xml字符串
	 * @return
	 */
	public static PrePayNotifyDataVo parsePrePayNotifyDataVoFromXml(String xml) {

		// 创建 XStream 对象
		XStream xstream = new XStream();
		// 设置别名（可选）
		xstream.alias("xml", PrePayNotifyDataVo.class);
		xstream.allowTypes(new Class[]{PrePayNotifyDataVo.class});

		Object obj = xstream.fromXML(xml);
		return (PrePayNotifyDataVo) obj;
	}

	public static <T> T convertXmlToObject(String xml, Class<T> clazz) throws IOException {
		XmlMapper xmlMapper = new XmlMapper();
		return xmlMapper.readValue(xml, clazz);
	}

	/**
	 * 对象转xml
	 *
	 * @param obj 对象
	 * @return
	 */
	public static String toXml(Object obj) {
		xStream = getXStream(obj.getClass());
		return XmlUtils.xStream.toXML(obj);
	}
}
